<?php

namespace App\Admin\Actions\VipPurchase;

use App\Models\VipPurchase;
use App\Models\User;
use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;
use Encore\Admin\Actions\Response;
use Carbon\Carbon;

class VipPurchaseCancel extends RowAction
{
    public $name = '取消';
	
	/**
	 * @param VipPurchase $model
	 * @return Response
	 */
    public function handle(Model $model)
    {
    	if ($model->paid_at == '') {
		    return $this->response()->error('会员订单未支付');
	    } elseif ($model->refund_status != 'pending') {
		    return $this->response()->error('目标会员订单已退款');
	    } 
	    $vipPurchase = VipPurchase::find($model->id);
	    $vipPurchase->update(['refund_status'=>"refused",'cancelled_at'=>Carbon::now()]);
	    $user = User::find($vipPurchase->user_id);

	    if(strtotime($user->vip_expired_at) < strtotime("+30 days")){
	    	$user->update(['grade'=>"normal"]);

	    }else{

	    	$user->update(['vip_expired_at'=>Carbon::parse($user->vip_expired_at)->subDays(30)]);
	    }

	    cashier($model->paid_method)->refundVip($vipPurchase);


	    return $this->response()->success('会员付费已取消')->refresh();
    }
	
	public function dialog()
	{
		$this->confirm('确定取消当前订单，请谨慎操作?');
	}
}
